// arch-tag: 226e7406-e08e-4540-b4a5-3b7b0911d905
package de.yvert.jingle.tools;

import de.yvert.jingle.ToneMapper;
import de.yvert.jingle.hdr.HdrImage2D;
import de.yvert.jingle.ldr.LdrImage2D;

/**
 * @author Ulf Ochsenfahrt
 */
public class NormalizeToneMapper implements ToneMapper
{

public void map(HdrImage2D in, LdrImage2D out)
{
	float[] from = in.getData();
	byte[] to = out.getData();
	
	// FIXME: What if from[0] is NaN?
	float min = from[0];
	float max = from[0];
	
	for (int i = 0; i < from.length/4; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			int offset = 4*i+j;
			// the odd comparisons are supposed to handle NaNs correctly
			if (!(from[offset] < max)) max = from[offset];
			if (!(from[offset] > min)) min = from[offset];
		}
	}
	
	float factor = 1/(max-min);
	for (int i = 0; i < from.length; i++)
		to[i] = LdrImage2D.clamp(factor*(from[i]-min));
}

}
